<template>
  <div class="top">
    <el-button @click="add">添加商品</el-button>
  </div>
  <el-table :data="tableData.data" border style="width: 100%">
    <el-table-column prop="id" label="ID" width="80" />
    <el-table-column prop="name" label="商品名称" />
    <el-table-column prop="price" label="价格/元" />
    <el-table-column prop="stock" label="库存" />

    <el-table-column prop="createdDate" label="操作">
      <template #default="scope">
        <el-button type="primary" @click="handleEdit(scope.row)"
          >编辑</el-button
        >
        <el-button type="danger" @click="handleDelete(scope.row.id)"
          >删除</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-dialog v-model="show" title="添加修改商品" @close="close">
    <el-form class="login-form">
      <el-form-item label="商品名称">
        <el-input v-model="loginForm.name" type="text" placeholder="商品名称">
        </el-input>
      </el-form-item>
      <el-form-item label="商品价格">
        <el-input v-model="loginForm.price" type="number" placeholder="价格">
        </el-input>
      </el-form-item>
      <el-form-item label="商品库存">
        <el-input v-model="loginForm.stock" type="number" placeholder="库存">
        </el-input>
      </el-form-item>
      <el-form-item label="提交">
        <el-button type="primary" @click="goodAdd">提交</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useUser } from "@/store/user.js";
import request from "../utils/request";
const show = ref(false);
const store = useUser();
const tableData = reactive({
  data: [],
});
const loginForm = ref({
  name: "",
  price: 0,
  stock: 0,
});
function getList() {
  request.get("/goods").then((res) => {
    tableData.data = res.data;
    console.log(res);
  });
}
function add() {
  show.value = true;
}
function goodAdd() {
  let data = loginForm.value;
  if (data.id) {
    request.put("/goods/" + data.id, data).then((res) => {
      console.log(res);
      ElMessage.success("提交成功");
      show.value = false;
      getList();
    });
  } else {
    request.post("/goods", data).then((res) => {
      console.log(res);
      ElMessage.success("提交成功");
      getList();
      show.value = false;
    });
  }
}
function close() {
  loginForm.value = {};
}
function handleEdit(e) {
  console.log(e);
  loginForm.value = e;
  show.value = true;
}
function handleDelete(e) {
  console.log(e);
  ElMessageBox.confirm("确定删除吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    request.delete("/goods/" + e).then((res) => {
      console.log(res);
      ElMessage.success("删除成功");
      getList();
    });
  });
}

onMounted(() => {
  tableData.data = store.goodsList;
  getList();
});
</script>
<style scoped>
.top {
  text-align: right;
  margin-bottom: 10px;
}
</style>
